<template>
  <div class="main">
    <!-- 检索区,查询表单 -->
    <div class="search">
      <!-- 表单组件 -->
      <el-form
        :inline="true"
        ref="searchFromRef"
        :model="gm"
        class="searchForm"
      >
        <!-- 表单项 -->
        <el-form-item label="商品名:" style="width: 200px" prop="goodsName">
          <el-input placeholder="请输入商品名" v-model="gm.goodsName" />
        </el-form-item>

        <el-form-item label="商品分类:" style="width: 200px" prop="categoryId">
          <el-input placeholder="请输入商品分类" v-model="gm.categoryId" />
        </el-form-item>

        <!-- 表单项 -->
        <el-form-item
          label="商品状态:"
          style="width: 200px"
          prop="goodsSellStatus"
        >
          <el-select v-model="gm.goodsSellStatus" placeholder="请选择状态">
            <el-option label="在售" value="0" />
            <el-option label="下架" value="1" />
          </el-select>
        </el-form-item>
        <!-- 表单项 -->
      </el-form>
      <el-button
        color="#909399"
        plain
        :icon="Search"
        @click="search"
        style="width: 75px"
        >查询</el-button
      >
      <el-button
        color="#e6a23c"
        plain
        :icon="Refresh"
        @click="resetSearch"
        style="width: 75px"
        >重置</el-button
      >
    </div>

    <!-- 操作区 -->
    <div class="action">
      <el-button
        color="#409eff"
        plain
        :icon="Plus"
        @click="add"
        style="margin-left: 10px"
        >新增</el-button
      >
      <el-button type="danger" plain :icon="Delete" @click="deleteAll"
        >批量删除</el-button
      >
    </div>

    <!-- 数据展示区 -->
    <div class="data">
      <!-- 表格 -->
      <div class="grid">
        <el-table
          :data="tableData"
          style="width: 100%"
          :header-cell-style="headerCellStyle"
          @row-click="rowClick"
          ref="tableRef"
        >
          <el-table-column
            type="selection"
            width="50"
            align="center"
            header-align="center"
          />
          <el-table-column
            prop="goodsId"
            label="ID"
            width="100"
            align="center"
            header-align="center"
          />
          <el-table-column
            prop="goodsName"
            label="商品名"
            width="200"
            align="center"
            header-align="center"
            show-overflow-tooltip
          />
          <el-table-column
            prop="goodsCoverImg"
            label="商品图片"
            width="120"
            align="center"
            header-align="center"
          >
            <template #default="scope">
              <div
                class="row-avatar"
                :style="'background-image:url(' + scope.row.goodsCoverImg + ')'"
              ></div>
            </template>
          </el-table-column>

          <el-table-column
            prop="category.name"
            label="商品分类"
            width="120"
            align="center"
            header-align="center"
          />
          <el-table-column
            prop="goodsIntro"
            label="商品简介"
            width="200"
            align="center"
            header-align="center"
            show-overflow-tooltip
          />
          <el-table-column
            prop="originalPrice"
            label="商品价格"
            width="100"
            align="center"
            header-align="center"
          />

          <el-table-column
            prop="sellingPrice"
            label="商品实际售价"
            width="150"
            align="center"
            header-align="center"
            show-overflow-tooltip
          />

          <el-table-column
            prop="stockNum"
            label="商品库存数量"
            width="150"
            align="center"
            header-align="center"
          />

          <el-table-column
            prop="createTime"
            label="商品添加时间"
            width="180"
            align="center"
            header-align="center"
          />
          <el-table-column
            prop="updateTime"
            label="商品修改时间"
            width="180"
            align="center"
            header-align="center"
          />

          <el-table-column
            prop="goodsSellStatus"
            label="商品上架状态"
            width="200"
            align="center"
            header-align="center"
          >
            <template #default="scope">
              <el-switch
                @change="switchChange2(scope.row)"
                v-model="scope.row.goodsSellStatus"
                class="ml-2"
                :class="
                  scope.row.goodsSellStatus === true
                    ? 'el-switch-enabled'
                    : 'el-switch-disabled'
                "
              />&nbsp;&nbsp;<span v-if="scope.row.goodsSellStatus === true"
                >已上架</span
              ><span v-if="scope.row.goodsSellStatus === false">已下架</span>
            </template>
          </el-table-column>

          <el-table-column fixed="right" label="操作" min-width="200">
            <template #default="scope">
              <el-button
                color="#409eff"
                :icon="Edit"
                style="width: 70px"
                @click="edit(scope.row)"
                plain
                >编辑</el-button
              >
              <el-button
                type="danger"
                plain
                :icon="Delete"
                @click="removeById(scope.row)"
                style="width: 70px"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-pageNum="pageInfo.pageNum"
          v-model:pageNum-size="pageInfo.size"
          :pageNum-sizes="[10, 15, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
          background
          @change="paginate"
        />
      </div>
    </div>
  </div>

  <el-dialog
    v-model="show"
    :title="title"
    width="700"
    draggable
    :close-on-click-modal="false"
    @close="close"
  >
    <!-- 新增表单 -->
    <el-form ref="sfRef" :model="gfm">
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="商品名:"
            label-width="100"
            prop="goodsName"
            :rules="[
              {
                required: true,
                message: '请输入商品名',
                trigger: 'blur',
              },
            ]"
          >
            <el-input v-model="gfm.goodsName" />
          </el-form-item>
          <!-- <el-form-item label="商品介绍:" label-width="100" prop="goodsIntro">
            <el-input v-model="gfm.goodsIntro" />
          </el-form-item> -->
          <el-form-item
            label="商品价格:"
            label-width="100"
            prop="originalPrice"
          >
            <el-input v-model="gfm.originalPrice" type="number" />
          </el-form-item>
          <el-form-item label="实际价格:" label-width="100" prop="sellingPrice">
            <el-input
              v-model="gfm.sellingPrice"
              type="number"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="库存数量:" label-width="100" prop="stockNum">
            <el-input v-model="gfm.stockNum" type="number" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="商品主图："
            label-width="100"
            prop="goodsCoverImg"
          >
            <el-upload
              class="avatar"
              action="/api/uploads/avatar"
              :show-file-list="false"
              :on-success="avatarSuccess"
            >
              <div
                class="preview"
                v-if="gfm.goodsCoverImg"
                :style="'background-image:url(' + gfm.goodsCoverImg + ')'"
              ></div>
              <el-icon class="icon" v-else>
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- TODO:关联分类 -->

      <el-form-item label="详细信息:" label-width="100" prop="goodsIntro">
        <el-input
          type="textarea"
          :rows="4"
          placeholder="请输入商品信息"
          v-model="gfm.goodsIntro"
          style="width: 92%"
        />
      </el-form-item>
    </el-form>

    <!-- 对话框按钮，#插槽: 组件空出来，允许用户更改组件内容。由组件使用者定义 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="submitForm"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- <h1>{{ gm.birthRange }}</h1> -->
</template>

<script setup>
import goodsInfoApi from "@/api/GoodsInfoApi";
import { reactive, ref } from "vue";
import { onMounted, toRaw, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Delete,
  Edit,
  Search,
  Share,
  Upload,
  Refresh,
  Plus,
} from "@element-plus/icons-vue";

//当组件挂载结束之后调用
onMounted(() => {
  search();
  document.title = "植物表型数据管理系统";
});

//响应式对象
const tableData = ref([]);
function paginate() {
  search();
}

// 分页信息
const pageInfo = ref({
  pageNum: 1,
  size: 10,
  total: 0,
});
//头像上传成功时的回调函数
function avatarSuccess(resp, file) {
  if (resp.success) {
    gfm.value.goodsCoverImg = resp.url;
  }
}

// 当页码和页码大小改变时触发

function search() {
  let params = gm.value; //查询条件
  goodsInfoApi
    .findAll(pageInfo.value.pageNum, pageInfo.value.size, params)
    .then((result) => {
      if (result.code == 0) {
        console.log(result.data.list);
        tableData.value = result.data.list;
        pageInfo.value.total = result.data.total;
        pageInfo.value.pageNum = result.data.pageNo;
        pageInfo.value.size = result.data.pageSize;
        tableData.value.forEach((item) => {
          item.goodsSellStatus = item.goodsSellStatus == 0 ? true : false;
        });
      }
    });
}

// 搜索条表单双向数据绑定
const gm = ref({
  goodsName: "",
  goodsSellStatus: "",
});

// // 表单实例的引用
let searchFromRef;
function resetSearch() {
  // 重置查询表单
  searchFromRef.resetFields();
}
// 定义表格实例
let tableRef;
//当点击表格时触发
function rowClick(row) {
  tableRef.toggleRowSelection(row);
}

// 删除操作逻辑
function deleteAll() {
  // 从表格中选中的行
  let rows = tableRef.getSelectionRows();
  let ids = []; //id数组
  for (let row of rows) {
    ids.push(row.goodsId);
  }
  //执行删除操作
  deleteById(ids);
}
//根据id数组批量删除
function deleteById(ids) {
  // 判断是否选中了要删除的记录
  if (ids.length == 0) {
    ElMessage({
      message: "请选中要删除的记录！",
      type: "warning",
    });
  } else {
    ElMessageBox.confirm("是否确定删除选中的记录吗？", "Warning", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      goodsInfoApi
        .removeAll(ids)
        .then((resp) => {
          if (resp.code == 0) {
            ElMessage({
              type: "success",
              message: "删除成功",
            });
            search(); //刷新
          }
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "删除操作取消",
          });
        });
    });
  }
}
//  按id删除
function removeById(row) {
  let goodsInfo = toRaw(row);
  deleteById([goodsInfo.goodsId]);
}

// 对话框是否显示
const show = ref(false);

// 定义对话框内容
const userFormModel = ref({
  goodsCoverImg: "",
  goodsName: "",
  goodsIntro: "",
  categoryId: "",
  goodsDetailContent: "",
  originalPrice: "",
  sellingPrice: "",
  stockNum: "",
});
// 对话框内容别名
const gfm = userFormModel;

// 对话框标题
const title = ref("新增商品");
// 弹出新增
function add() {
  show.value = true;
  title.value = "新增商品";
  // 下一个时间滴答中赋值
  nextTick(() => {
    gfm.value = {}; //给新增/修改表单赋值
  });
}
// 提交表单
function submitForm() {
  let goodsInfo = gfm.value;
  if (goodsInfo.goodsId) {
    //修改
    submitEdit(goodsInfo);
  } else {
    //新增
    submitAdd(goodsInfo);
  }
}

// 新增逻辑
function submitAdd(goodsInfo) {
  goodsInfoApi.save(goodsInfo).then((resp) => {
    if (resp.code == 0) {
      ElMessage({
        type: "success",
        message: "新增成功",
      });
      search();
    } else {
      ElMessage({
        type: "error",
        message: resp.msg,
      });
    }
  });
  show.value = false;
}

let sfRef;
// 关闭对话框，重置表单
function close() {
  sfRef.resetFields();
}

// 修改操作
function edit(row) {
  let goodsInfo = toRaw(row);
  // 浅拷贝
  row = Object.assign({}, goodsInfo);
  show.value = true;
  title.value = "修改商品";
  // 下一个时间滴答中赋值
  nextTick(() => {
    gfm.value = row; //给新增/修改表单赋值
  });
}
// 提交表单执行逻辑
function submitEdit(goodsInfo) {
  goodsInfo.goodsSellStatus = goodsInfo.goodsSellStatus === true ? 0 : 1;
  goodsInfoApi.update(toRaw(goodsInfo)).then((resp) => {
    if (resp.code == 0) {
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      search();
    } else {
      ElMessage({
        type: "error",
        message: resp.msg,
      });
    }
  });
  show.value = false;
}

//表头样式
function headerCellStyle() {
  return {
    background: " #f4f4f5",
    textAlign: "center",
    color: "#909399",
  };
}

// 切换状态
function switchChange2(row) {
  let goodsInfo = toRaw(row);
  goodsInfo.goodsSellStatus = goodsInfo.goodsSellStatus === true ? 1 : 0;
  goodsInfoApi.updataByState(goodsInfo).then((resp) => {
    console.log(resp);
    if (resp.code == 0) {
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      search();
    } else {
      ElMessage({
        type: "error",
        message: resp.msg,
      });
    }
  });
}
</script>

<style scoped>
/* 定义不同状态下的 CSS 类 */
.el-switch-enabled {
  --el-switch-on-color: #13c75b;
  --el-switch-off-color: #13c75b;
}
.el-switch-disabled {
  --el-switch-on-color: #f56c6c;
  --el-switch-off-color: #f56c6c;
}
.pagination {
  margin-top: 20px;
}
.search {
  display: flex;
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 5px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.search > form .el-form-item {
  flex-grow: 1;
  margin-right: 10px;
  margin-bottom: 0;
}
.action {
  margin-top: 10px;
  width: 100%;
  display: flex;
  padding: 10px 0;
  border-radius: 5px;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.1);
}
.dialog-footer {
  margin-top: 20px;
}
.data {
  margin-top: 5px;
  padding: 15px 10px;
  border: 1px solid #ccc;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.avatar {
  width: 120px;
  height: 120px;
  border: 1px solid #ccc;
}

.avatar .icon {
  width: 120px;
  height: 120px;
}

.avatar .preview {
  width: 120px;
  height: 120px;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: contain;
}

.row-avatar {
  width: 50px;
  height: 50px;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: contain;
  margin: 0 auto;
  border-radius: 50%; /* 设置为50%使头像为圆形 */
  overflow: hidden; /* 防止图片在圆外显示 */
}
</style>
